package com.gitee.ly.openfeign;

import feign.Request;
import io.seata.core.context.RootContext;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.*;

public class DefaultLightRegistryFeignClientFinalRequestHandle implements LightRegistryFeignClientFinalRequestHandle {
    private static final int MAP_SIZE = 16;

    private static final boolean existSeata;

    static {
        existSeata = ClassUtils.isPresent("io.seata.core.context.RootContext", null);
    }

    @Override
    public Request getFinalRequest(Request request) {
        if (existSeata) {
            //默认支持seataRPC
            String xid = RootContext.getXID();
            if (StringUtils.isEmpty(xid)) {
                return request;
            }
            Map<String, Collection<String>> headers = new HashMap<>(MAP_SIZE);
            headers.putAll(request.headers());

            List<String> seataXid = new ArrayList<>();
            seataXid.add(xid);
            headers.put(RootContext.KEY_XID, seataXid);

            return Request.create(request.method(), request.url(), headers, request.body(),
                    request.charset());
        }
        return request;
    }
}
